"""
素材列表页面

显示和管理所有素材的页面
"""

import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from pathlib import Path
import sys
import os

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from src.gui.main_app import BasePage
from src.gui.design_system import (DesignSystem, create_card_frame,
                                  create_primary_button, create_secondary_button,
                                  create_success_button, create_danger_button)


class MaterialListPage(BasePage):
    """素材列表页面"""
    
    def __init__(self, parent, app):
        super().__init__(parent, app)
        self.materials = []  # 素材数据
        self.filtered_materials = []  # 过滤后的素材
        self.current_filter = "all"
        
    def create_page(self):
        """创建页面内容"""
        self.frame = ttk.Frame(self.parent)
        
        # 页面标题
        self.create_header()
        
        # 工具栏
        self.create_toolbar()
        
        # 素材列表
        self.create_material_list()
        
        # 加载示例数据
        self.load_sample_data()
    
    def create_header(self):
        """创建页面标题"""
        header_frame = ttk.Frame(self.frame)
        header_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 标题区域
        title_container = ttk.Frame(header_frame)
        title_container.pack(side="left", fill="x", expand=True)

        title_label = ttk.Label(
            title_container,
            text="📋 素材列表",
            style='Title.TLabel'
        )
        title_label.pack(side="left")

        # 副标题
        subtitle_label = ttk.Label(
            title_container,
            text="管理和查看所有素材文件",
            style='Muted.TLabel'
        )
        subtitle_label.pack(side="left", padx=(DesignSystem.SPACING['md'], 0))

        # 操作按钮区域
        action_frame = ttk.Frame(header_frame)
        action_frame.pack(side="right")

        # 刷新按钮
        refresh_btn = create_secondary_button(
            action_frame,
            text="🔄 刷新",
            command=self.refresh_materials
        )
        refresh_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))
    
    def create_toolbar(self):
        """创建工具栏"""
        toolbar_frame = create_card_frame(self.frame, "筛选和操作")
        toolbar_frame.pack(fill="x", pady=(0, DesignSystem.SPACING['xl']))

        # 第一行：筛选控件
        filter_row = ttk.Frame(toolbar_frame)
        filter_row.pack(fill="x", pady=(0, DesignSystem.SPACING['md']))

        # 类型筛选
        filter_container = ttk.Frame(filter_row)
        filter_container.pack(side="left")

        ttk.Label(filter_container, text="类型筛选:", style='Heading.TLabel').pack(side="left")

        self.filter_var = tk.StringVar(value="all")
        filter_combo = ttk.Combobox(
            filter_container,
            textvariable=self.filter_var,
            values=[("all", "全部类型"), ("video", "视频"), ("image", "图片"), ("audio", "音频")],
            state="readonly",
            width=12
        )
        filter_combo.pack(side="left", padx=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['lg']))
        filter_combo.bind("<<ComboboxSelected>>", self.on_filter_changed)

        # 搜索框
        search_container = ttk.Frame(filter_row)
        search_container.pack(side="left")

        ttk.Label(search_container, text="搜索:", style='Heading.TLabel').pack(side="left")
        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(search_container, textvariable=self.search_var, width=25)
        search_entry.pack(side="left", padx=(DesignSystem.SPACING['sm'], 0))
        search_entry.bind("<KeyRelease>", self.on_search_changed)

        # 第二行：操作按钮
        action_row = ttk.Frame(toolbar_frame)
        action_row.pack(fill="x")

        # 左侧按钮组
        left_actions = ttk.Frame(action_row)
        left_actions.pack(side="left")

        add_btn = create_primary_button(
            left_actions,
            text="➕ 添加素材",
            command=self.add_material
        )
        add_btn.pack(side="left", padx=(0, DesignSystem.SPACING['sm']))

        # 右侧按钮组
        right_actions = ttk.Frame(action_row)
        right_actions.pack(side="right")

        export_btn = create_secondary_button(
            right_actions,
            text="📤 导出列表",
            command=self.export_list
        )
        export_btn.pack(side="right", padx=(DesignSystem.SPACING['sm'], 0))

        delete_btn = create_danger_button(
            right_actions,
            text="🗑️ 删除选中",
            command=self.delete_selected
        )
        delete_btn.pack(side="right")
    
    def create_material_list(self):
        """创建素材列表"""
        list_frame = create_card_frame(self.frame, "素材列表")
        list_frame.pack(fill="both", expand=True)

        # 列表容器
        list_container = ttk.Frame(list_frame)
        list_container.pack(fill="both", expand=True)

        # 创建Treeview
        columns = ('name', 'type', 'size', 'duration', 'category', 'status', 'created')
        self.tree = ttk.Treeview(list_container, columns=columns, show='headings', height=15)

        # 设置列标题和宽度
        column_config = {
            'name': ('📄 文件名', 220),
            'type': ('🏷️ 类型', 80),
            'size': ('📊 大小', 100),
            'duration': ('⏱️ 时长', 80),
            'category': ('📂 分类', 120),
            'status': ('🔄 状态', 100),
            'created': ('📅 创建时间', 150)
        }

        for col, (title, width) in column_config.items():
            self.tree.heading(col, text=title)
            self.tree.column(col, width=width, anchor='center' if col != 'name' else 'w')

        # 滚动条
        v_scrollbar = ttk.Scrollbar(list_container, orient="vertical", command=self.tree.yview)
        h_scrollbar = ttk.Scrollbar(list_container, orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=v_scrollbar.set, xscrollcommand=h_scrollbar.set)

        # 布局
        self.tree.grid(row=0, column=0, sticky="nsew")
        v_scrollbar.grid(row=0, column=1, sticky="ns")
        h_scrollbar.grid(row=1, column=0, sticky="ew")

        list_container.grid_rowconfigure(0, weight=1)
        list_container.grid_columnconfigure(0, weight=1)

        # 绑定事件
        self.tree.bind("<Double-1>", self.on_item_double_click)
        self.tree.bind("<Button-3>", self.show_context_menu)

        # 添加空状态提示
        self.create_empty_state(list_frame)

    def create_empty_state(self, parent):
        """创建空状态提示"""
        self.empty_frame = ttk.Frame(parent)

        empty_icon = ttk.Label(
            self.empty_frame,
            text="📁",
            font=(DesignSystem.FONTS['family_primary'], 48)
        )
        empty_icon.pack(pady=(50, DesignSystem.SPACING['lg']))

        empty_title = ttk.Label(
            self.empty_frame,
            text="暂无素材",
            style='Heading.TLabel'
        )
        empty_title.pack()

        empty_desc = ttk.Label(
            self.empty_frame,
            text="点击「添加素材」按钮开始上传您的第一个素材文件",
            style='Muted.TLabel'
        )
        empty_desc.pack(pady=(DesignSystem.SPACING['sm'], DesignSystem.SPACING['xl']))

        add_first_btn = create_primary_button(
            self.empty_frame,
            text="➕ 添加第一个素材",
            command=self.add_material
        )
        add_first_btn.pack()
    
    def load_sample_data(self):
        """加载示例数据"""
        sample_materials = [
            {
                'name': 'product_video_001.mp4',
                'type': 'video',
                'size': '25.6 MB',
                'duration': '00:15',
                'category': 'AI素材',
                'status': '已处理',
                'created': '2024-01-15 10:30'
            },
            {
                'name': 'model_photo_001.jpg',
                'type': 'image',
                'size': '2.1 MB',
                'duration': '-',
                'category': '模特试穿',
                'status': '已审核',
                'created': '2024-01-15 09:15'
            },
            {
                'name': 'background_music.mp3',
                'type': 'audio',
                'size': '5.8 MB',
                'duration': '03:45',
                'category': '背景音乐',
                'status': '待处理',
                'created': '2024-01-14 16:20'
            },
            {
                'name': 'product_showcase.mov',
                'type': 'video',
                'size': '45.2 MB',
                'duration': '00:30',
                'category': '产品展示',
                'status': '已处理',
                'created': '2024-01-14 14:10'
            },
            {
                'name': 'lifestyle_image.png',
                'type': 'image',
                'size': '3.4 MB',
                'duration': '-',
                'category': '产品使用',
                'status': '已审核',
                'created': '2024-01-13 11:45'
            }
        ]
        
        self.materials = sample_materials
        self.filtered_materials = sample_materials.copy()
        self.update_material_list()
    
    def update_material_list(self):
        """更新素材列表显示"""
        # 清空现有项目
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 添加过滤后的素材
        for material in self.filtered_materials:
            # 根据类型设置图标
            type_icons = {
                'video': '🎬',
                'image': '🖼️',
                'audio': '🎵'
            }
            icon = type_icons.get(material['type'], '📄')
            
            # 根据状态设置颜色标签
            status_tags = {
                '已处理': 'processed',
                '已审核': 'approved',
                '待处理': 'pending'
            }
            tag = status_tags.get(material['status'], '')
            
            self.tree.insert('', 'end', values=(
                f"{icon} {material['name']}",
                material['type'],
                material['size'],
                material['duration'],
                material['category'],
                material['status'],
                material['created']
            ), tags=(tag,))
        
        # 配置标签颜色
        self.tree.tag_configure('processed', background='#d5f4e6')
        self.tree.tag_configure('approved', background='#cce5ff')
        self.tree.tag_configure('pending', background='#fff2cc')
    
    def on_filter_changed(self, event=None):
        """筛选条件改变"""
        self.apply_filters()
    
    def on_search_changed(self, event=None):
        """搜索条件改变"""
        self.apply_filters()
    
    def apply_filters(self):
        """应用筛选条件"""
        filter_type = self.filter_var.get()
        search_text = self.search_var.get().lower()
        
        self.filtered_materials = []
        
        for material in self.materials:
            # 类型筛选
            if filter_type != "all" and material['type'] != filter_type:
                continue
            
            # 搜索筛选
            if search_text and search_text not in material['name'].lower():
                continue
            
            self.filtered_materials.append(material)
        
        self.update_material_list()
    
    def on_item_double_click(self, event):
        """双击项目事件"""
        selection = self.tree.selection()
        if selection:
            item = self.tree.item(selection[0])
            material_name = item['values'][0]
            messagebox.showinfo("素材详情", f"查看素材: {material_name}")
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        item = self.tree.identify_row(event.y)
        if item:
            self.tree.selection_set(item)
            
            context_menu = tk.Menu(self.frame, tearoff=0)
            context_menu.add_command(label="查看详情", command=self.view_details)
            context_menu.add_command(label="编辑信息", command=self.edit_material)
            context_menu.add_separator()
            context_menu.add_command(label="下载文件", command=self.download_file)
            context_menu.add_command(label="删除素材", command=self.delete_material)
            
            context_menu.tk_popup(event.x_root, event.y_root)
    
    def add_material(self):
        """添加素材"""
        self.app.show_page("add_material")
    
    def delete_selected(self):
        """删除选中的素材"""
        selection = self.tree.selection()
        if not selection:
            messagebox.showwarning("提示", "请先选择要删除的素材")
            return
        
        if messagebox.askyesno("确认删除", f"确定要删除选中的 {len(selection)} 个素材吗？"):
            for item in selection:
                self.tree.delete(item)
            messagebox.showinfo("成功", "素材删除成功")
    
    def export_list(self):
        """导出素材列表"""
        file_path = filedialog.asksaveasfilename(
            title="导出素材列表",
            defaultextension=".csv",
            filetypes=[("CSV文件", "*.csv"), ("Excel文件", "*.xlsx")]
        )
        if file_path:
            messagebox.showinfo("成功", f"素材列表已导出到: {file_path}")
    
    def view_details(self):
        """查看素材详情"""
        messagebox.showinfo("提示", "查看详情功能开发中...")
    
    def edit_material(self):
        """编辑素材信息"""
        messagebox.showinfo("提示", "编辑功能开发中...")
    
    def download_file(self):
        """下载文件"""
        messagebox.showinfo("提示", "下载功能开发中...")
    
    def delete_material(self):
        """删除单个素材"""
        if messagebox.askyesno("确认删除", "确定要删除这个素材吗？"):
            selection = self.tree.selection()
            if selection:
                self.tree.delete(selection[0])
                messagebox.showinfo("成功", "素材删除成功")
    
    def refresh_materials(self):
        """刷新素材列表"""
        self.load_sample_data()
        messagebox.showinfo("成功", "素材列表已刷新")
    
    def refresh(self):
        """页面刷新"""
        self.refresh_materials()
